/**
 * @desc 用户管理模块
 */
const express = require('express')
const router = express.Router()
const User = require('../models/user')
const Category = require('../models/category')
const Content = require('../models/content')
// 分页数据限制
const LIMIT = 10

router.use((req, res, next) => {
  if (!req.userInfo.isAdmin) {
    res.json({
      code: '-1',
      message: '该账号不是管理员账号!'
    })
  } else {
    next()
  }
})

// 首页
router.get('/', (req, res, next) => {
  res.render('admin/index', {
    userInfo: req.userInfo
  })
})

// 用户管理
router.get('/user', (req, res) => {
  /**
   * [data description]
   *
   * 从数据库中查找数据 渲染到页面
   *
   * limit(Number): 限制获取的数据条数
   *
   * skip(Number): 忽略数据的条数
   *
   * 每页显示2条
   * 1. 1, 2 skip 0
   * 2. 3, 4 skip 2
   * (当前页 - 1)*limit
   *
   */
  // 获取页数
  // let INDEX_PAGE = req.query
  let {
    page
  } = req.query

  // INDEX_PAGE = Number(page) || 1
  let INDEX_PAGE = Number(page || 1)
  // 当前页数
  let AllPages = 0
  let count = 0
  let skip = 0
  // 判断查找数据的数量
  User.countDocuments().then(_count => {
    count = _count
    AllPages = Math.ceil(count / LIMIT)
    INDEX_PAGE = Math.min(INDEX_PAGE, AllPages)
    INDEX_PAGE = Math.max(INDEX_PAGE, 1)
    skip = (INDEX_PAGE - 1) * LIMIT
    return Promise.resolve()
  }).then(() => {
    // 查找数据
    User.find().sort({
      _id: -1
    }).limit(LIMIT).skip(skip).then(data => {
      res.render('admin/user_index', {
        userInfo: req.userInfo,
        userList: data,
        page: INDEX_PAGE,
        allPages: AllPages,
        count,
        limit: LIMIT,
				route: 'user'
      })
    })
  })
})

// 分类管理
router.get('/category', (req, res) => {
  let {
    page
  } = req.query

  // INDEX_PAGE = Number(page) || 1
  let INDEX_PAGE = Number(page || 1)
  // 当前页数
  let AllPages = 0
  let count = 0
  let skip = 0
  // 判断查找数据的数量
  Category.countDocuments().then(_count => {
    count = _count
    AllPages = Math.ceil(count / LIMIT)
    INDEX_PAGE = Math.min(INDEX_PAGE, AllPages)
    INDEX_PAGE = Math.max(INDEX_PAGE, 1)
    skip = (INDEX_PAGE - 1) * LIMIT
    return Promise.resolve()
  }).then(() => {
    /**
     * [categories description]
     * @decs sort 排序 接收两个值 1 升序 -1 降序
     */
    Category.find().sort({
      _id: -1
    }).limit(LIMIT).skip(skip).then(categories => {
      res.render('admin/category_index', {
        userInfo: req.userInfo,
        categories,
        page: INDEX_PAGE,
        allPages: AllPages,
        count,
        limit: LIMIT,
				route: 'category'
      })
    })
  })
})

// 添加分类管理页面
router.get('/category/add', (req, res) => {
  res.render('admin/category_add.html', {
    userInfo: req.userInfo
  })
})

// 添加分类
router.post('/category/add', (req, res) => {
  // 名称是否为空
  let {
    name
  } = req.body
  if (!name) {
    res.render('admin/error.html', {
      userInfo: req.userInfo,
      message: '用户名不能为空 !',
      type: 'panel-danger'
    })
  } else {
    // 数据是否存在
    Category.findOne({
      name
    }).then(rs => {
      if (!!rs) {
        return Promise.reject()
      } else {
        return new Category({
          name
        }).save()
      }
    }).then(() => {
      res.redirect(302, '/admin/category')
    }, () => {
      res.render('admin/error.html', {
        userInfo: req.userInfo,
        message: '该数据已经存在 !',
        type: 'panel-danger'
      })
    })
  }
})

// 修改分类信息
router.get('/category/edit', (req, res) => {
  let {
    id
  } = req.query || {}
  // 获取修改的信息
  Category.findOne({
    _id: id
  }).then(category => {
    if (!category) {
      res.render('admin/error.html', {
        userInfo: req.userInfo,
        message: '不存在此分类!',
        type: 'panel-danger'
      })
      return Promise.reject()
    }
    res.render('admin/category_edit.html', {
      userInfo: req.userInfo,
      name: category.name
    })
  })
})

// 修改分类
router.post('/category/edit', (req, res) => {
  // 名称是否为空
  let {
    name
  } = req.body
  let id = req.query.id || ''
  if (!name) {
    res.render('admin/error.html', {
      userInfo: req.userInfo,
      message: '用户名不能为空 !',
      type: 'panel-danger'
    })
  } else {
    Category.findOne({
      // id 不等于当前id
      _id: {
        $ne: id
      },
      name
    }).then(category => {
      if (!!category) {
        res.render('admin/error.html', {
          userInfo: req.userInfo,
          message: '该分类已存在 !',
          type: 'panel-danger'
        })
        return Promise.reject()
      } else {
        return Category.update({
          _id: id
        }, {
          name
        })
      }
    }).then(() => {
      res.redirect(302, '/admin/category')
    })
  }
})

// 删除分类信息
router.get('/category/del', (req, res) => {
  // 1. 查找是否存在
  // 1.1 如果不存在 报错
  // 2. 如果存在 根据id 删除这条数据
  let {
    id
  } = req.query || {}
  // 获取修改的信息
  Category.findOne({
    _id: id
  }).then(category => {
    if (!category) {
      res.render('admin/error.html', {
        userInfo: req.userInfo,
        message: '不存在该用户!',
        type: 'panel-danger'
      })
      return Promise.reject()
    }
    return Category.deleteOne({
      _id: id
    })
  }).then(() => {
    res.redirect(302, '/admin/category')
  })
})

// 内容首页
router.get('/content', (req, res) => {
  let {
    page
  } = req.query

  // INDEX_PAGE = Number(page) || 1
  let INDEX_PAGE = Number(page || 1)
  // 当前页数
  let AllPages = 0
  let count = 0
  let skip = 0
  // 判断查找数据的数量
  Content.countDocuments().then(_count => {
    count = _count
    AllPages = Math.ceil(count / LIMIT)
    INDEX_PAGE = Math.min(INDEX_PAGE, AllPages)
    INDEX_PAGE = Math.max(INDEX_PAGE, 1)
    skip = (INDEX_PAGE - 1) * LIMIT
    return Promise.resolve()
  }).then(() => {
    /**
     * [categories description]
     * @decs sort 排序 接收两个值 1 升序 -1 降序
     */
    Content.find().sort({
      addTime: -1
    }).limit(LIMIT).skip(skip).populate(['category', 'user']).then(contents => {
      res.render('admin/content_index', {
        userInfo: req.userInfo,
        contents,
        page: INDEX_PAGE,
        allPages: AllPages,
        count,
        limit: LIMIT,
				route: 'content'
      })
    })
  })
})

// 添加内容
router.get('/content/add', (req, res) => {
  // 读取数据
  Category.find().sort({
    _id: -1
  }).then(categories => {
    if (!categories) {
      res.status(400).send('数据库错误!')
    } else {
      res.render('admin/content_add', {
        userInfo: req.userInfo,
        categories
      })
    }
  })
})

// 内容保存
router.post('/content/add', (req, res) => {
  // console.log(req.body)
  let {
    category,
    title,
    description,
    content
  } = req.body
  if (category == '') {
    res.render('admin/error.html', {
      userInfo: req.userInfo,
      message: '内容类型不能为空!',
      type: 'panel-danger'
    })
  } else if (title == '') {
    res.render('admin/error.html', {
      userInfo: req.userInfo,
      message: '内容标题不能为空!',
      type: 'panel-danger'
    })
  } else {
    new Content({
      category,
      title,
      description,
      content,
      user: req.userInfo._id.toString()
    }).save().then(rs => {
      if (!!rs) {
        res.redirect(302, '/admin/content')
      } else {
        res.status(400).send('数据库错误')
      }
    })
  }
})

// 修改内容
router.get('/content/edit', (req, res) => {
  // 获取 id
  let {
    id
  } = req.query
  let categories = []
  Category.find().sort({
    _id: -1
  }).then(data => {
    categories = data
    if (!categories) {
      res.status(400).send('数据库错误!')
      return Promise.reject()
    } else {
      return Content.findOne({
        _id: id
      }).populate('category')
    }
  }).then(data => {
    if (!data) {
      res.render('admin/error.html', {
        userInfo: req.userInfo,
        message: '不存在此内容!',
        type: 'panel-danger'
      })
      return Promise.reject()
    }
    res.render('admin/content_edit.html', {
      userInfo: req.userInfo,
      categories: categories,
      data
    })
  })
})

// 提交修改内容
router.post('/content/edit', (req, res) => {
  let id = req.query.id || ''
  let {
    category,
    title,
    description,
    content
  } = req.body
  if (category == '') {
    res.render('admin/error.html', {
      userInfo: req.userInfo,
      message: '内容类型不能为空!',
      type: 'panel-danger'
    })
  } else if (title == '') {
    res.render('admin/error.html', {
      userInfo: req.userInfo,
      message: '内容标题不能为空!',
      type: 'panel-danger'
    })
  } else {
    Content.updateOne({
      _id: id
    }, {
      category,
      title,
      description,
      content
    }).then((data) => {
      if (!!data) {
        res.redirect(302, '/admin/content')
      } else {
        res.status(400).send('数据库错误')
      }
    })
  }
})

// 删除内容
router.get('/content/del', (req, res) => {
  let id = req.query.id || ''
  // 获取修改的信息
  Content.findOne({
    _id: id
  }).then(data => {
    if (!data) {
      res.render('admin/error.html', {
        userInfo: req.userInfo,
        message: '不存在该用户!',
        type: 'panel-danger'
      })
      return Promise.reject()
    }
    return Content.deleteOne({
      _id: id
    })
  }).then(() => {
    res.redirect(302, '/admin/content')
  })
})

module.exports = router
